<?php
class Sql {
    private static $conn;
    private static $tableName;
    private static $conditions = [];
    private static $data = [];

    // 初始化数据库连接和表名
    public static function init($tableName) {
        global $conn;
        self::$conn = $conn;
        self::$tableName = $tableName;
        self::$conditions = [];
        self::$data = [];
        return new static();
    }

    // 设置条件
    public function where($conditions = []) {
        if (is_array($conditions)) {
            self::$conditions = $conditions;
        } elseif (func_num_args() == 2) {
            $field = func_get_arg(0);
            $value = func_get_arg(1);
            self::$conditions[$field] = $value;
        } else {
            throw new Exception("where 方法需要一个数组或两个参数");
        }
        return $this;
    }

    // 设置要更新或插入的数据
    public function setData($data = []) {
        if (is_array($data)) {
            self::$data = $data;
        } elseif (func_num_args() == 2) {
            $field = func_get_arg(0);
            $value = func_get_arg(1);
            self::$data[$field] = $value;
        } else {
            throw new Exception("setData 方法需要一个数组或两个参数");
        }
        return $this;
    }

    // 查询方法
    public function query() {
        // 如果没有条件，则返回表中所有数据
        if (empty(self::$conditions)) {
            $sql = "SELECT * FROM `" . self::$tableName . "`";
            $stmt = self::$conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("SQL 准备失败: " . self::$conn->error);
            }
        } else {
            // 构建 WHERE 条件字符串
            $whereConditions = [];
            foreach (self::$conditions as $field => $value) {
                $whereConditions[] = "`$field` = ?";
            }
            $whereString = implode(" AND ", $whereConditions);

            // 构建 SQL 查询语句
            $sql = "SELECT * FROM `" . self::$tableName . "` WHERE " . $whereString;

            // 准备预处理语句
            if (!$stmt = self::$conn->prepare($sql)) {
                throw new Exception("SQL 准备失败: " . self::$conn->error);
            }

            // 获取参数类型字符串和参数数组
            $types = '';
            $params = [];
            foreach (self::$conditions as $value) {
                if (is_int($value)) {
                    $types .= 'i';
                } elseif (is_float($value)) {
                    $types .= 'd';
                } elseif (is_string($value)) {
                    $types .= 's';
                } else {
                    throw new Exception("不支持的参数类型: " . gettype($value));
                }
                $params[] = $value;
            }

            // 绑定参数
            $stmt->bind_param($types, ...$params);
        }

        // 执行查询
        if (!$stmt->execute()) {
            throw new Exception("查询执行失败: " . $stmt->error);
        }

        // 获取结果
        $result = $stmt->get_result();
        $rows = [];
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }

        // 关闭语句
        $stmt->close();

        // 清空条件
        self::$conditions = [];

        return $rows;
    }

    // 更新方法
    public function update() {
        // 检查是否有条件
        if (empty(self::$conditions)) {
            throw new Exception("更新操作必须有条件");
        }

        // 构建 SET 字段字符串
        $setFields = [];
        foreach (self::$data as $field => $value) {
            $setFields[] = "`$field` = ?";
        }
        $setString = implode(", ", $setFields);

        // 构建 WHERE 条件字符串
        $whereConditions = [];
        foreach (self::$conditions as $field => $value) {
            $whereConditions[] = "`$field` = ?";
        }
        $whereString = implode(" AND ", $whereConditions);

        // 构建 SQL 更新语句
        $sql = "UPDATE `" . self::$tableName . "` SET " . $setString . " WHERE " . $whereString;

        // 准备预处理语句
        if (!$stmt = self::$conn->prepare($sql)) {
            throw new Exception("SQL 准备失败: " . self::$conn->error);
        }

        // 获取参数类型字符串和参数数组
        $types = '';
        $params = [];
        foreach (self::$data as $value) {
            if (is_int($value)) {
                $types .= 'i';
            } elseif (is_float($value)) {
                $types .= 'd';
            } elseif (is_string($value)) {
                $types .= 's';
            } else {
                throw new Exception("不支持的参数类型: " . gettype($value));
            }
            $params[] = $value;
        }
        foreach (self::$conditions as $value) {
            if (is_int($value)) {
                $types .= 'i';
            } elseif (is_float($value)) {
                $types .= 'd';
            } elseif (is_string($value)) {
                $types .= 's';
            } else {
                throw new Exception("不支持的参数类型: " . gettype($value));
            }
            $params[] = $value;
        }

        // 绑定参数
        $stmt->bind_param($types, ...$params);

        // 执行更新
        if (!$stmt->execute()) {
            throw new Exception("更新执行失败: " . $stmt->error);
        }

        // 关闭语句
        $stmt->close();

        // 清空条件和数据
        self::$conditions = [];
        self::$data = [];

        return $this;
    }

    // 插入方法
    public function insert() {
        // 构建字段和值字符串
        $fields = [];
        $values = [];
        foreach (self::$data as $field => $value) {
            $fields[] = "`$field`";
            $values[] = "?";
        }
        $fieldsString = implode(", ", $fields);
        $valuesString = implode(", ", $values);

        // 构建 SQL 插入语句
        $sql = "INSERT INTO `" . self::$tableName . "` ($fieldsString) VALUES ($valuesString)";

        // 准备预处理语句
        if (!$stmt = self::$conn->prepare($sql)) {
            throw new Exception("SQL 准备失败: " . self::$conn->error);
        }

        // 获取参数类型字符串和参数数组
        $types = '';
        $params = [];
        foreach (self::$data as $value) {
            if (is_int($value)) {
                $types .= 'i';
            } elseif (is_float($value)) {
                $types .= 'd';
            } elseif (is_string($value)) {
                $types .= 's';
            } else {
                throw new Exception("不支持的参数类型: " . gettype($value));
            }
            $params[] = $value;
        }

        // 绑定参数
        $stmt->bind_param($types, ...$params);

        // 执行插入
        if (!$stmt->execute()) {
            throw new Exception("插入执行失败: " . $stmt->error);
        }

        // 关闭语句
        $stmt->close();

        // 清空数据
        self::$data = [];

        return $this;
    }

    // 删除方法
    public function delete() {
        // 检查是否有条件
        if (empty(self::$conditions)) {
            throw new Exception("删除操作必须有条件");
        }

        // 构建 WHERE 条件字符串
        $whereConditions = [];
        foreach (self::$conditions as $field => $value) {
            $whereConditions[] = "`$field` = ?";
        }
        $whereString = implode(" AND ", $whereConditions);

        // 构建 SQL 删除语句
        $sql = "DELETE FROM `" . self::$tableName . "` WHERE " . $whereString;

        // 准备预处理语句
        if (!$stmt = self::$conn->prepare($sql)) {
            throw new Exception("SQL 准备失败: " . self::$conn->error);
        }

        // 获取参数类型字符串和参数数组
        $types = '';
        $params = [];
        foreach (self::$conditions as $value) {
            if (is_int($value)) {
                $types .= 'i';
            } elseif (is_float($value)) {
                $types .= 'd';
            } elseif (is_string($value)) {
                $types .= 's';
            } else {
                throw new Exception("不支持的参数类型: " . gettype($value));
            }
            $params[] = $value;
        }

        // 绑定参数
        $stmt->bind_param($types, ...$params);

        // 执行删除
        if (!$stmt->execute()) {
            throw new Exception("删除执行失败: " . $stmt->error);
        }

        // 关闭语句
        $stmt->close();

        // 清空条件
        self::$conditions = [];

        return $this;
    }
}

// 示例用法
// $mysqli = new mysqli("localhost", "username", "password", "database");
// if ($mysqli->connect_error) {
//     die("连接失败: " . $mysqli->connect_error);
// }

// // 查询操作
// $result = Sql::init($mysqli, "users")->where(["age" => 25])->query();
// print_r($result);

// // 更新操作
// Sql::init($mysqli, "users")->where(["id" => 1])->setData(["name" => "Alice"])->update();

// // 插入操作
// Sql::init($mysqli, "users")->setData(["name" => "Bob", "age" => 30])->insert();

// // 删除操作
// Sql::init($mysqli, "users")->where(["id" => 2])->delete();

// $mysqli->close();
?>